package com.hwadee.ems.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import com.hwadee.ems.util.UserHolder;

/**
 * @author EnosElinsa
 * @since 2024/06/19
 */
public class LoginInterceptor implements HandlerInterceptor {

    @SuppressWarnings("null")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断是否需要拦截 （ThreadLocal中是否有用户信息）
        if (UserHolder.getUser() == null) {
            // 2. 不存在，拦截
            response.setStatus(401);
            return false;
        }

        // 3. 存在，放行
        return true;    
    }

    @SuppressWarnings("null")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
    
}

